﻿using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Web;

namespace BENBUN.Utils.Web
{

    class APIFactory
    {
        private static string _apiToken;
        private static Boolean _apiSuccess;
        private static string _apiErrorBlock;
        private static string _apiErrorText;
        private static string _apiResponse;

        public static void qUploadFilesToRemoteUrl(string url, string[] files, string
logpath, NameValueCollection nvc)
        {

            long length = 0;
            string boundary = "----------------------------" +
            DateTime.Now.Ticks.ToString("x");


            HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest2.ContentType = "multipart/form-data; boundary=" +
            boundary;
            httpWebRequest2.Method = "POST";
            httpWebRequest2.KeepAlive = true;
            httpWebRequest2.Credentials =
            System.Net.CredentialCache.DefaultCredentials;

            Stream memStream = new System.IO.MemoryStream();

            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
            boundary + "\r\n");

            string formdataTemplate = "\r\n--" + boundary +
            "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

            foreach (string key in nvc.Keys)
            {
                string formitem = string.Format(formdataTemplate, key, nvc[key]);
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                memStream.Write(formitembytes, 0, formitembytes.Length);
            }


            memStream.Write(boundarybytes, 0, boundarybytes.Length);

            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";

            for (int i = 0; i < files.Length; i++)
            {
                if (files[i] != null)
                {
                    //string header = string.Format(headerTemplate, "file" + i, files[i]);
                    string header = string.Format(headerTemplate, "file", "test.txt");

                    byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

                    memStream.Write(headerbytes, 0, headerbytes.Length);
                    FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read);
                    byte[] buffer = new byte[1024];
                    int bytesRead = 0;

                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        memStream.Write(buffer, 0, bytesRead);
                    }
                    memStream.Write(boundarybytes, 0, boundarybytes.Length);
                    fileStream.Close();
                }
            }

            httpWebRequest2.ContentLength = memStream.Length;

            Stream requestStream = httpWebRequest2.GetRequestStream();

            memStream.Position = 0;
            byte[] tempBuffer = new byte[memStream.Length];
            memStream.Read(tempBuffer, 0, tempBuffer.Length);
            memStream.Close();
            requestStream.Write(tempBuffer, 0, tempBuffer.Length);
            requestStream.Close();

            WebResponse webResponse2 = httpWebRequest2.GetResponse();
            Stream stream2 = webResponse2.GetResponseStream();
            StreamReader reader2 = new StreamReader(stream2);

            string responseString = reader2.ReadToEnd();
            responseString = responseString + " ";
            webResponse2.Close();
            httpWebRequest2 = null;
            webResponse2 = null;
        }

        public static Boolean doUploadFile(string uri, Hashtable parameters, string file)
        {
            string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");

            string headerParameters = "";
            string paramSeperator = "?";
            //foreach (DictionaryEntry s in parameters)
            //{
            //    headerParameters = headerParameters + paramSeperator + s.Key + "=" + s.Value;
            //    paramSeperator = "&";
            //}

            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri + headerParameters);
            httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
            httpWebRequest.Method = "POST";
            httpWebRequest.KeepAlive = true;
            httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;

            System.Net.ServicePointManager.Expect100Continue = false;

            // Get the boundry in bytes
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            foreach (DictionaryEntry s in parameters)
            {
                headerParameters = headerParameters + "--" + boundary + "\r\nContent-Disposition: form-data;";
                headerParameters = headerParameters + " name=\"" + s.Key + "\"\r\n\r\n";
                headerParameters = headerParameters + s.Value + "\r\n";
            }
            headerParameters = headerParameters + "--" + boundary + "\r\n";

            // Get the header for the file upload
            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\";filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";

            // Add the filename to the header and convert the header to a byte array
            //string header = headerParameters + string.Format(headerTemplate, "file", file);
            string header = headerParameters + string.Format(headerTemplate, "file", "test.txt");
            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

            // Add all of the content up.
            httpWebRequest.ContentLength = new FileInfo(file).Length + headerbytes.Length + (boundarybytes.Length * 2) + 2;

            // Get the output stream
            Stream requestStream = httpWebRequest.GetRequestStream();

            // Write out the starting boundry
            requestStream.Write(boundarybytes, 0, boundarybytes.Length);

            // Write the header including the filename.
            requestStream.Write(headerbytes, 0, headerbytes.Length);

            // Open up a filestream.
            FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);

            // Use 4096 for the buffer
            byte[] buffer = new byte[4096];

            int bytesRead = 0;
            // Loop through whole file uploading parts in a stream.
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                requestStream.Write(buffer, 0, bytesRead);
                requestStream.Flush();
            }

            boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

            // Write out the trailing boundry
            requestStream.Write(boundarybytes, 0, boundarybytes.Length);

            // Close the request and file stream
            requestStream.Close();
            fileStream.Close();

            WebResponse webResponse = httpWebRequest.GetResponse();

            Stream responseStream = webResponse.GetResponseStream();
            StreamReader responseReader = new StreamReader(responseStream);

            string responseString = responseReader.ReadToEnd();

            // Close response object.
            webResponse.Close();


            return true;
        }
        public static String doAPI(string uri, string parameters)
        {
            _apiErrorText = "";
            _apiResponse = "";

            //parameters  = HttpUtility.UrlEncode(parameters);
            WebRequest webRequest = WebRequest.Create(uri);


            //string ProxyString = 
            //   System.Configuration.ConfigurationManager.AppSettings
            //   [GetConfigKey("proxy")];
            //webRequest.Proxy = new WebProxy (ProxyString, true);
            //Commenting out above required change to App.Config
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method = "POST";

            byte[] bytes = Encoding.UTF8.GetBytes(parameters);
            Stream os = null;
            try
            { // send the Post
                webRequest.ContentLength = bytes.Length;   //Count bytes to send
                os = webRequest.GetRequestStream();
                os.Write(bytes, 0, bytes.Length);         //Send it
            }
            catch (WebException ex)
            {
                _apiErrorText += ex.Message;
                _apiErrorText += "\r\nurl = " + uri;
            }
            finally
            {
                if (os != null)
                {
                    os.Close();
                }
            }

            try
            { // get the response
                WebResponse webResponse = webRequest.GetResponse();
                if (webResponse == null)
                {
                    _apiResponse = null;
                    return _apiResponse;
                }
                StreamReader sr = new StreamReader(webResponse.GetResponseStream());

                _apiResponse = sr.ReadToEnd().Trim();
                return _apiResponse;
            }
            catch (WebException ex)
            {
                _apiErrorText += "Invalid web response \r\n\n";
                _apiErrorText += ex.Message;
                _apiErrorText += "\r\n\nurl = " + uri;

            }
            _apiResponse = null;
            return _apiResponse;

        }


        public static Boolean APISuccess
        {
            get { return _apiSuccess; }
        }
        public static string APIErrorText
        {
            get { return _apiErrorText; }
        }

        public static string APIResponse
        {
            get { return _apiResponse; }
        }
   
    }
}
